package com.qiyun.dinghuohui.utils;

import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileViewer {
	public static List<String> fileList = new ArrayList<String>();

	public static boolean deleteFile(String path, int retrycount) {
		boolean breturn = false;
		File file = null;
		while (retrycount > 0) {
			retrycount--;
			file = new File(path);
			breturn = file.delete();
			if (breturn) {
				break;
			}
		}
		return breturn;
	}

	/**
	 * @param path
	 *            文件路径
	 * @param suffix
	 *            后缀名
	 * @param isdepth
	 *            是否遍历子目录
	 * @return
	 */
	public static List getListFiles(String path, String suffix, boolean isdepth) {
		fileList.clear();
		File file = new File(path);
		return FileViewer.listFile(file, suffix, isdepth);
	}

	public static List listFile(File f, String suffix, boolean isdepth) {
		// 是目录，同时需要遍历子目录
		if (f.isDirectory()) {
			File[] t = f.listFiles();
			for (int i = 0; i < t.length; i++) {
				if ((t[i].isDirectory() && isdepth) || (!t[i].isDirectory())) {
					listFile(t[i], suffix, isdepth);
				}
			}
		} else {
			String filePath = f.getAbsolutePath();

			// System.out.println("suffix = " + suffix);
			if (suffix == "" || suffix == null) {
				// 后缀名为null则为所有文件
				System.out.println("----------------");
				fileList.add(filePath);
			} else {
				int begIndex = filePath.lastIndexOf(".");// 最后一个.(即后缀名前面的.)的索引
				String tempsuffix = "";

				if (begIndex != -1)// 防止是文件但却没有后缀名结束的文件
				{
					tempsuffix = filePath.substring(begIndex + 1,
							filePath.length());
				}

				if (tempsuffix.equals(suffix)) {
					fileList.add(filePath);
				}
				// System.out.println("|||||||||||||||||||");
			}

		}
		return fileList;
	}

	/**
	 * 方法追加文件：使用FileWriter
	 * 
	 * @param fileName
	 * @param content
	 */
	public static void appendMethod(String fileName, String content) {
		try {
			// 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
			Log.d(fileName, content);
			File file = new File(fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter writer = new FileWriter(fileName, true);
			writer.write(content + "\r\n");
			writer.close();
		} catch (IOException e) {
			Log.d("", "fileName->" + fileName + "  content->" + content);
			e.printStackTrace();
		}
	}

	public static void saveCrashInfoToFile(String fileName, Throwable ex) {
		for (StackTraceElement se : ex.getStackTrace()) {
			appendMethod(fileName, se.toString());
		}
	}
}
